package com.fatan.xiaopacai.mvvm.viewmodel

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.fatan.xiaopacai.base.BaseViewModel
import com.fatan.xiaopacai.base.FORMAT_0
import com.fatan.xiaopacai.base.TAG
import com.fatan.xiaopacai.mvvm.model.RandomShaiZiMaxDbNum
import com.fatan.xiaopacai.room.AppDataBase
import com.fatan.xiaopacai.room.randomshaizi.RandomShaiZiEntity
import com.fatan.xiaopacai.util.JsonUtil
import java.text.SimpleDateFormat
import java.util.Locale

/**
 * @author: WangYeTong
 * @date: 2023/12/27 17:07
 * @remake:
 */
class RandomShaiZiRecordViewModel : BaseViewModel() {
    private val _randomShaiZiRecordDataList = mutableStateOf<List<RandomShaiZiEntity>>(listOf())
    val randomShaiZiRecordDataList: MutableState<List<RandomShaiZiEntity>>
        get() = _randomShaiZiRecordDataList

    private val _dataFormat by lazy { SimpleDateFormat(FORMAT_0, Locale.getDefault()) }

    fun getAllRecordData() = serverAwait {
        val tempList = AppDataBase.database.randomShaiZiDao().getAll().reversed()
        if (tempList.size > RandomShaiZiMaxDbNum) {
            _randomShaiZiRecordDataList.value = tempList.subList(0, RandomShaiZiMaxDbNum)
            //多出来的给删掉
            val externalList = tempList.subList(RandomShaiZiMaxDbNum, tempList.size)
            externalList.forEach { item ->
                Log.i(TAG, "随机摇色子删除数据:${JsonUtil.toJson(item)}")
                AppDataBase.database.randomShaiZiDao().delete(item)
            }

        } else {
            _randomShaiZiRecordDataList.value = tempList
        }
        Log.i(TAG, "随机摇骰子查询所有历史记录: ${JsonUtil.toJson(_randomShaiZiRecordDataList.value)}")
    }

    fun getFormatDateString(mill: Long): String? = _dataFormat.format(mill)
}